import { useState } from "react";
import unselect from "./assets/unselect.png";
import select from "./assets/select.png";
import "./App.css";
import { useMemo } from "react";

function App() {
  const [goods, setGoods] = useState([
    { name: "手机", price: 4999, selected: false, count: 1 },
    { name: "PS5 Pro", price: 5999, selected: false, count: 1 },
    { name: "PC", price: 23999, selected: false, count: 1 },
    { name: "Switch", price: 1999, selected: false, count: 1 },
    { name: "键盘", price: 799, selected: false, count: 1 },
  ]);

  let changeCount = (e, index) => {
    let narr = [...goods];
    if (goods[index].count <= 1 && e.target.innerText === "-") return;

    if (e.target.innerText === "-") {
      narr[index].count = goods[index].count - 1;
    } else {
      narr[index].count = goods[index].count + 1;
    }
    setGoods(narr);
  };

  let changeSelect = (index) => {
    let narr = [...goods];
    narr[index].selected
      ? (narr[index].selected = false)
      : (narr[index].selected = true);
    setGoods(narr);
  };

  let checkAll = useMemo(() => {
    // useMemo ⽤来做缓存⽤的，只有当⼀个依赖项改变的时候才会发⽣变化，否则拿缓存的值，就不⽤在每次渲染的时候再做计算
    return goods.filter((item) => item.selected).length === goods.length;
  }, [goods]);

  let selectAll = () => {
    let narr = [...goods];
    if (checkAll) {
      narr.forEach((item) => {
        item.selected = false;
      });
    } else {
      narr.forEach((item) => {
        item.selected = true;
      });
    }
    setGoods(narr);
  };

  let deleteGood = (index) => {
    let narr = [...goods];
    narr.splice(index, 1);
    setGoods(narr);
  };

  let totalPrice = useMemo(() => {
    let selected = goods.filter((item) => item.selected);
    let price = 0;
    selected.forEach((item) => {
      price += item.price * item.count;
    });
    return price;
  }, [goods]);

  return (
    <>
      <ul>
        {goods.map((good, index) => (
          <li key={good.name}>
            <img
              src={good.selected ? select : unselect}
              onClick={() => changeSelect(index)}
              alt="未选中"
            />
            {good.name}
            <span>{good.price}</span>
            <button onClick={(e) => changeCount(e, index)}>-</button>
            <span>{good.count}</span>
            <button onClick={(e) => changeCount(e, index)}>+</button>
            <button onClick={() => deleteGood(index)}>删除</button>
          </li>
        ))}
      </ul>
      <div>
        <img
          src={checkAll ? select : unselect}
          onClick={selectAll}
          alt="全选"
        />
      </div>
      <div>
        <span>总价:{totalPrice}</span>
        <button>结算</button>
      </div>
    </>
  );
}

export default App;
